package com.yonyou.iuap.shell.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.yonyou.iuap.base.utils.BaseToolsUtils;
import com.yonyou.iuap.shell.service.intf.IFtpService;
import com.yonyou.iuap.utils.PropertyUtil;

@Service
public class FtpServiceImp implements IFtpService {
	private static Logger logger = Logger.getLogger(FtpServiceImp.class);

	public void login(FTPClient ftpClient) throws Exception {
		//获取FTP服务器地址
        String ftpServer = BaseToolsUtils.getPropertiesValue("encrypt_ftp_ip");
        //获取FTP服务器端口
        int ftpPort = StringUtils.isEmpty(BaseToolsUtils.getPropertiesValue("encrypt_ftp_port"))?21:Integer.valueOf(BaseToolsUtils.getPropertiesValue("encrypt_ftp_port"));
        //获取FTP用户账号
        String ftpUser = BaseToolsUtils.getPropertiesValue("encrypt_ftp_user");
        //获取FTP用户密码
        String ftpPwd = BaseToolsUtils.getPropertiesValue("encrypt_ftp_pwd");
        ftpClient.setDataTimeout(60000);       //设置传输超时时间为60秒 
        ftpClient.setConnectTimeout(60000);       //连接超时为60秒
 
        try {
            // 链接到FTP服务器
            ftpClient.connect(ftpServer, ftpPort);
 
            logger.debug("链接到FTP服务器：" + ftpServer + "成功..");
 
            // 开始登陆服务器
            boolean boo = ftpClient.login(ftpUser, ftpPwd);
 
            if (boo) {
 
            	logger.debug("登陆到FTP服务器：" + ftpServer + "成功..");
 
            } else {
 
            	logger.debug("登陆到FTP服务器：" + ftpServer + "失败..");
 
                logout(ftpClient);//退出/断开FTP服务器链接
            }
 
        } catch (Exception e) {
 
            e.printStackTrace();
 
            logger.error("登陆到FTP服务器：" + ftpServer + "失败..");
        }
		
	}

	public void logout(FTPClient ftpClient) throws Exception {
		ftpClient.logout();//退出登陆
		 
        logger.debug("已退出FTP远程服务器..");
 
        if (ftpClient.isConnected()) {
 
            ftpClient.disconnect();//断开链接
 
            logger.debug("已断开FTP服务器链接..");
        }
		
	}

	public boolean uploadFile(FTPClient ftpClient, String fileNewName, InputStream inputStream) throws Exception{
		return uploadFile(ftpClient, "",fileNewName, inputStream);
	}
			
	public boolean uploadFile(FTPClient ftpClient, String remotePath,
			String fileNewName, InputStream inputStream) throws Exception {
		try {
			 login(ftpClient);
            String ftpRemotePath = BaseToolsUtils.getPropertiesValue("encrypt_ftp_path");//ftp目的地仓库位置,而文件实例地址=仓库位置+上传指定位置
            //设置被动模式 
            // 设置PassiveMode传输  
            ftpClient.enterLocalPassiveMode();
 
            // 设置以二进制流的方式传输
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
 
            //设置字符集
            ftpClient.setControlEncoding("GBK");
            //创建目录结构
            if (remotePath != null && !"".equals(remotePath.trim())) {
                String[] pathes = remotePath.split("/");
                for (String onepath : pathes) {
                    if (onepath == null || "".equals(onepath.trim())) {
                        continue;
                    }
                    onepath = new String(onepath.getBytes("GBK"), "iso-8859-1");
                    if (!ftpClient.changeWorkingDirectory(onepath)) {
                        ftpClient.makeDirectory(onepath);//创建FTP服务器目录
                        ftpClient.changeWorkingDirectory(onepath);//改变FTP服务器目录
                    }
                }
 
            }
 
            boolean boo = ftpClient.storeFile(new String(fileNewName.getBytes("GBK"), "iso-8859-1"), inputStream);
 
            if (boo) {
 
                logger.debug("文件上传成功..");
 
            } else {
 
                logger.debug("文件上传失败..");
            }
 
            return boo;
        } catch (Exception e) {
 
            e.printStackTrace();
            return false;
 
        } finally {
 
            try {
 
                if (null != inputStream) {
 
                    inputStream.close();
                }
 
                logout(ftpClient);//退出/断开FTP服务器链接
 
            } catch (IOException e) {
 
                logger.debug("关闭链接失败..");
 
                e.printStackTrace();
            }
        }
	}

	public List listFile(FTPClient ftpClient, String remotePath)
			throws Exception {
		login(ftpClient);
		//设置目录字符集
        String remp = new String(remotePath.getBytes("GBK"), "iso-8859-1");
 
        FTPListParseEngine engine = ftpClient.initiateListParsing(remotePath);
        List<FTPFile> remoteFiles = Arrays.asList(engine.getNext(25));
 
        List list = new ArrayList();
 
        if (remoteFiles != null && remoteFiles.size() != 0) {
 
            logger.debug("目录" + remotePath + "下的文件列表..");
 
        } else {
 
            logger.debug("目录" + remotePath + "下无文件内容..");
        }
        //递归目录文件
        for (FTPFile ftpFile : remoteFiles) {
 
            Map<String, String> map = new HashMap<String, String>();
 
            map.put("fileName", ftpFile.getName());//文件名称
 
            map.put("fileSize", Long.toString(ftpFile.getSize()));//文件大小
 
            //文件时间
            map.put("fileTime", new SimpleDateFormat("yyyy/MM/dd kk:mm:ss").format(ftpFile.getTimestamp().getTime()));
 
            list.add(map);
        }
 
        logout(ftpClient);//退出/断开FTP服务器链接
 
        return list;
	}

	public InputStream downFileByFtp(FTPClient ftpClient, String remotePath,
			String fileName) throws Exception {
		FTPFile[] fs;
        InputStream is = null;
        try {
        	login(ftpClient);
            //设置被动模式   
            ftpClient.enterLocalPassiveMode();
            // 设置以二进制流的方式传输
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            //设置编辑格式
            ftpClient.setControlEncoding("GBK");
 
            remotePath = remotePath.substring(0, remotePath.lastIndexOf(fileName));
            fs = ftpClient.listFiles(remotePath);//递归目标目录
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {//查找目标文件
                    is = ftpClient
                            .retrieveFileStream(new String((remotePath + fileName).getBytes("GBK"), "iso-8859-1"));
                    break;
                }
            }
 
        } catch (IOException e) {
 
            e.printStackTrace();
        } finally {
            logout(ftpClient);//退出/断开FTP服务器链接
        }
        return is;
	}

	public boolean delFile(FTPClient ftpClient, String pathName) throws Exception {
		try {
			login(ftpClient);
            return ftpClient.deleteFile(pathName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            logout(ftpClient);//退出/断开FTP服务器链接
        }
		return false;
	}

}
